import Axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'antd'
// import { setToken, getToken, removeToken } from '@/utils/auth'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import { BaseResponse, CustomAxiosRequestConfig } from '@/interface'

const service = Axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  timeout: 50000,
})

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    NProgress.start()

    // eslint-disable-next-line no-param-reassign
    config.headers.token = getToken()

    return config
  },
  (error: { message: string }) => {
    message.error(error.message)
  },
)

service.interceptors.response.use(
  (response: AxiosResponse): Promise<any> => {
    const { data } = response

    if (data.code !== 200) {
      message.error(data.message)
      if (data.code === 416) {
        // token失效 跳转login
        window.location.href = '/login'
      }
      return Promise.reject(data)
    }
    if (!data) {
      return Promise.reject(data)
    }

    NProgress.done()
    return Promise.resolve(data)
  },
  (error: { message: string }) => {
    message.destroy()
    message.error('网络异常')

    NProgress.done()
    return Promise.reject(error)
  },
)

const request = <T = any>(config: CustomAxiosRequestConfig): Promise<T> => {
  return new Promise((resolve, reject) => {
    service
      .request<BaseResponse<T>>(config)
      .then((res: AxiosResponse) => resolve(res.data))
      .catch((err: { message: string }) => reject(err))
  })
}

request.get = <T = any>(url: string, params?: object): Promise<T> => request({
  method: 'get',
  url,
  params,
})

request.post = <T = any>(url: string, params?: object): Promise<T> => request({
  method: 'post',
  url,
  data: params,
})

request.delete = <T = any>(url: string, params?: object): Promise<T> => request({
  method: 'delete',
  url,
  params,
})

request.put = <T = any>(url: string, params?: object): Promise<T> => request({
  method: 'put',
  url,
  data: params,
})

request.patch = <T = any>(url: string, params?: object): Promise<T> => request({
  method: 'patch',
  url,
  data: params,
})

export default request
